
package com.example.demo.redis.client;

import com.example.demo.redis.able.LockInterface;
import com.example.demo.redis.util.RedissonUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class RedissonLockClient {

    @Autowired
    private RedissonClient redissonClient;


/**
     * 获取读写锁
     */

    public RLock getLock(LockInterface lockInterface) {
        return getLock(lockInterface, null);
    }


/**
     * 获取读写锁
     */

    public RLock getLock(LockInterface lockInterface, String key) {
        String cacheKey = RedissonUtils.getCacheKey(lockInterface, key);
        return redissonClient.getLock(cacheKey);
    }


/**
     * 获取并尝试加锁
     */

    public RLock getLockAndTry(LockInterface lockInterface) {
        return getLockAndTry(lockInterface, null);
    }


/**
     * 获取并尝试加锁
     */

    public RLock getLockAndTry(LockInterface lockInterface, String key) {
        RLock rLock = getLock(lockInterface, key);
        boolean result = RedissonUtils.tryLock(rLock, lockInterface);
        return result ? rLock : null;
    }


/**
     * 获取读写锁
     */

    public RReadWriteLock getReadWriteLock(LockInterface lockInterface) {
        return getReadWriteLock(lockInterface, null);
    }


/**
     * 获取读写锁
     */

    public RReadWriteLock getReadWriteLock(LockInterface lockInterface, String key) {
        String cacheKey = RedissonUtils.getCacheKey(lockInterface, key);
        return redissonClient.getReadWriteLock(cacheKey);
    }


}

